<template>
  <div>
    <el-dialog
      @close="handleClose(false)"
      @open="handleOpen"
      close-on-press-escape
      v-dialogDrag
      title="编辑设备"
      :close-on-click-modal="false"
      :lock-scroll="false"
      :visible.sync="showDialog"
    >
      <el-tabs :tab-position="tabPosition" class="tabHight">
        <el-tab-pane label="详情">
          <el-form
            :model="deviceForm"
            :rules="deviceRules"
            ref="deviceForm"
            size="mini"
            label-width="80px"
            class="tabHight_auto"
          >
            <el-form-item label="Token:" prop="token">
              <el-input
                disabled
                v-model="deviceForm.token"
                placeholder="请输入token"
              ></el-input>
            </el-form-item>
            <el-form-item label="名称:" prop="name">
              <el-input
                v-model="deviceForm.name"
                placeholder="请输入名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="设备类型:" prop="deviceTypeToken">
              <el-select
                v-model="deviceForm.deviceTypeToken"
                placeholder="请选择"
                size="mini"
                class="w100"
              >
                <el-option
                  v-for="item in deviceTypeList"
                  :key="item.token"
                  :label="item.name"
                  :value="item.token"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="描述:" prop="comments">
              <el-input
                type="textarea"
                v-model="deviceForm.comments"
                placeholder="请输入描述"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="设备台账">
          <el-table
            size="small"
            :data="deviceForm.deviceAccounts"
            border
            stripe
          >
            <el-table-column
              label="序号"
              width="70"
              type="index"
              align="center"
            >
            </el-table-column>
            <el-table-column prop="accuracy" label="炉温精度" align="center">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.accuracy"
                  placeholder="请输入"
                  size="small"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="temperatureUpper"
              label="温度区间上界"
              align="center"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.temperatureUpper"
                  placeholder="请输入"
                  size="small"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="temperatureLower"
              label="温度区间下界"
              align="center"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.temperatureLower"
                  placeholder="请输入"
                  size="small"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="offset" label="死区/补偿值" align="center">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.offset"
                  placeholder="请输入"
                  size="small"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="offset"
              label="操作"
              align="center"
              width="120px"
            >
              <!-- eslint-disable-next-line -->
              <template slot="header" slot-scope="scope">
                <div class="flex-x flex-space" style="">
                  <div>操作</div>
                  <el-button type="primary" size="small" @click="addAccount"
                    >添加</el-button
                  >
                </div>
              </template>
              <template slot-scope="scope">
                <el-button
                  size="small"
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="delAccount(scope.row, scope.$index)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="元数据">
          <metaData
            :editmetaData="editmetaData"
            :isedit="isedit"
            @sendmetaDatas="sendmetaData"
          />
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="handleClose(false)">取 消</el-button>
        <el-button
          v-permission="[3, 'button']"
          size="mini"
          type="primary"
          :loading="btnLoading"
          @click="submitForm('deviceForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MetaData from "../../opensite/metaData.vue";
import { TOKEN_RULES } from "@/utils/local";
import { editDevice, getDeviceLists, getAccounts } from "@/api/device";
import { getDeviceTypes } from "@/api/deviceType";
import { generateId } from "@/utils";
export default {
  name: "devicePageEditDevice",
  props: {
    editdevice: {
      type: Boolean,
      default: false,
    },
    deviceToken: {
      type: String,
      default: "",
    },
  },
  components: {
    MetaData,
  },
  data() {
    return {
      btnLoading: false,
      showDialog: false,
      tabPosition: "left",
      token: this.deviceToken,
      deviceForm: {
        token: "",
        name: "",
        deviceTypeToken: "",
        comments: "",
        id: "",
        metadata: {},
        deviceAccounts: [],
      },
      deviceTypeList: [],
      deviceRules: {
        token: TOKEN_RULES,
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        deviceTypeToken: [
          { required: true, message: "请选择设备类型", trigger: "blur" },
        ],
      },
      isedit: true, //true为编辑页进入，false为添加页进入
      editmetaData: [],
      metaDataJson: {},
    };
  },
  mounted() {},
  watch: {
    editdevice() {
      this.showDialog = this.editdevice;
    },
  },
  methods: {
    // 删除台账
    delAccount(row, index) {
      this.deviceForm.deviceAccounts.splice(index, 1);
    },
    // 添加设备台账
    addAccount() {
      this.deviceForm.deviceAccounts.push({
        temperatureUpper: "",
        accuracy: "",
        temperatureLower: "",
        offset: "",
        deviceId: "",
        token: "",
        metadata: {},
        // id: generateId(),
      });
    },

    //弹窗打开执行操作
    async handleOpen() {
      await this.getDeviceByToken();
    },
    // 弹窗关闭执行操作
    handleClose(isRefresh) {
      var param = { isRefresh: isRefresh, deviceToken: this.token };
      this.$emit("changeShow", param);
    },
    // 获取设备详情
    getDeviceByToken() {
      var that = this;
      var param = { includeAssignment: true, includeDeviceType: true };
      return getDeviceLists(param, `/${that.token}`).then((res) => {
        const r = res.data;
        that.deviceForm.token = r.token;
        that.deviceForm.deviceAccounts = r.deviceAccounts
          ? r.deviceAccounts
          : [];
        that.deviceForm.id = r.id;
        that.deviceForm.name = r.name;
        that.deviceForm.comments = r.comments;
        that.deviceForm.metadata = r.metadata;
        that.deviceForm.deviceTypeToken = r.deviceType.token;
        that.editmetaData = that.deviceForm.metadata;
        that.getDeviceTypeList();
      });
    },
    //获取设备类型列表
    getDeviceTypeList() {
      var that = this;
      getDeviceTypes().then((res) => {
        that.deviceTypeList = res.data.results;
      });
    },

    // 提交
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let formData = {};
          this.deviceForm.deviceAccounts.forEach((item, index) => {
            const isEmp =
              !item.temperatureUpper &&
              !item.temperatureLower &&
              !item.offset &&
              !item.accuracy;
            if (isEmp) {
              this.deviceForm.deviceAccounts.splice(index, 1);
            }
          });
          formData = Object.assign({}, this.deviceForm);
          console.log("object :>> ", formData);

          formData.metadata = this.metaDataJson;
          this.btnLoading = true;
          editDevice(formData, this.token)
            .then(async (res) => {
              this.token = this.deviceForm.token;
              this.$msg({
                type: "success",
                message: "操作成功!",
              });
              this.showDialog = false;
              this.handleClose(true);
            })
            .finally((f) => {
              this.btnLoading = false;
            });
        } else {
          this.$msg("数据校验失败,请检查!");
          return false;
        }
      });
    },
    //元数据页回传
    sendmetaData(md) {
      this.metaDataJson = md;
    },
  },
};
</script>

<style scoped>
</style>